<script setup lang="ts">
import dayjs from "dayjs";
import { ref } from "vue";
import { debounce } from "lodash-es";
import { useRoute } from "vue-router";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore"; // ES 2015

import {
  ElButton,
  ElCard,
  ElCol,
  ElForm,
  ElFormItem,
  ElImage,
  ElInput,
  ElLink,
  ElMessage,
  ElMessageBox,
  ElRow,
  ElSpace,
  ElSwitch,
  UploadFile,
  ElRadioGroup,
  ElRadio,
  ElText,
  ElAlert,
} from "element-plus";
import { Warning } from "@element-plus/icons-vue";
import Editor from "@/components/common/Editor.vue";
import Uploader from "@/components/common/Uploader.vue";
import { ProInputNumber } from "@/modules/package/form";
import AppFooter from "@/components/common/AppFooter.vue";
import UploaderSingle from "@/components/common/UploaderSingle.vue";
import DateRangePicker from "@/components/common/DateRangePicker.vue";

import useForm from "@/hooks/useForm";
import useEnum from "@/hooks/useEnum";
import useRequest from "@/hooks/useRequest";
import { useAppTabs } from "@/modules/package/appTabs";

import router from "@/router";
import ApiActivity from "@/api/activity";

import { TActivity } from "@/global";

const { list: typeList } = useEnum("EnumActivityType");

dayjs.extend(isSameOrBefore);

const { params } = useRoute();
const { closeTab } = useAppTabs();

// 验证规则
const rules = {
  title: { required: true, message: "请输入活动标题" },
  title_img: { required: true, message: "请设置活动封面图" },
  title_small_img: { required: true, message: "请设置活动封面小图" },
  poster_img: { required: true, message: "请设置活动海报图" },
  // pic_content: { required: true, message: "请上传活动宣传图" },
  start_time: { required: true, message: "请选择活动时间" },
  act_time: { required: true, message: "请输入活动展示日期" },
  type: { required: true, message: "请选择活动类型" },

  sale_start_time: { required: true, message: "请选择售票时间" },

  address: { required: true, message: "请输入位置简称" },
  street: { required: true, message: "请输入活动详细地址" },
  longitude: { required: true, message: "请输入经度" },
  latitude: { required: true, message: "请输入纬度" },

  sponsor: { required: true, message: "请输入主办方" },

  act_desc: { required: true, message: "请输入活动详情" },
  purchase_notice: { required: true, message: "请输入购票须知" },
  exhibition_rules: { required: true, message: "请输入参展规则" },

  sort: { required: true, message: "请输入活动排序" },
};

const fileList = ref<any[]>([]);

// S 默认表单数据
const defaultModelValue: Partial<TActivity> = {
  is_show: 1,
  status: 0,
  is_refund: 0,
  act_status: 0,
  sort: 100,
  inv_status: 1,
  is_ticket: 2,
};

const { refForm, model, isFetching, submit, reset, onFetchResponse } = useForm<
  TActivity & {
    tag?: string;
  }
>(ApiActivity[params.id ? "activityModify" : "activityAdd"], {
  defaultModel: { ...defaultModelValue },
  formatModel(data) {
    const { value } = fileList;
    return {
      ...data,
      pic_content: value.map((e) => e.url).join(";"),
    };
  },
});

onFetchResponse(() => {
  if (!!params.id) {
    ElMessage.success("活动编辑成功！");
    router.go(-1);
    closeTab();
  } else {
    ElMessageBox.confirm("活动添加成功！", {
      type: "success",
      confirmButtonText: "返回列表",
      cancelButtonText: "继续添加",
      closeOnClickModal: false,
      showClose: false,
    })
      .then(() => {
        router.push("/activity/list");
        closeTab();
      })
      .catch(() => {
        // @ts-expect-error
        model.value = { ...defaultModelValue };
      });
  }
});

// 获取活动详情
const {
  isFetching: isFetchingWithDetail,
  data,
  onFetchResponse: onFetchResponseWithDetail,
} = useRequest(ApiActivity.activityDetail, {
  immediate: !!params.id,
  defaultParams: { id: +params.id },
});

onFetchResponseWithDetail(() => {
  const { detail } = data.value;

  model.value = { ...detail };

  try {
    if (detail.pic_content) {
      const list = detail.pic_content
        .split(";")
        .map((url: string, index: number) => ({ url, uid: index }));
      fileList.value = list || [];
    }
  } catch (err) {
    console.error(err);
  }
});

const pasteInput = ref();
// 经纬度粘贴事件
const pasteChange = debounce(() => {
  const { value } = pasteInput;
  if (value.trim()) {
    if (value.includes(",")) {
      const [lat, lon] = value.split(",");
      model.value.longitude = lon;
      model.value.latitude = lat;

      pasteInput.value = "";
    } else {
      if (value > -90 && value < 90) {
        // 纬度（不准确，纬度也在这个范围）
        model.value.latitude = value;
      } else if (value > -180 && value < 180) {
        // 经度
        model.value.longitude = value;
      }
    }
  }
}, 500);

/**
 * 上传图片成功
 */
const handleUploadSus = (url: string) => {
  fileList.value.push({
    url,
    uid: new Date().getTime(),
  });
};

/**
 * 删除图片前钩子：二次弹窗确认
 */
const handleBeforeRemove = () => ElMessageBox.alert("确定删除这张图片？");

/**
 * 移除图片
 */
const handleRemove = (uploadFile: UploadFile) => {
  const index = fileList.value.findIndex((e) => e.uid == uploadFile.uid);
  fileList.value.splice(index, 1);
};

// 提交
const handleSubmit = () => {
  submit().catch((err) => {
    // @ts-expect-error
    const [res] = Object.values(err)[0];
    ElMessage.error(res.message);
  });
};

const isSetCoverMode = ref(false);
/**设置封面图 */
const setCoverFromFileList = ({ url }: any) => {
  model.value.title_img = url;
  isSetCoverMode.value = false;
};

// 改变is_show状态时，需要根据情况更新status状态
const changeIsShow = (e) => {
  if (data.value?.detail.status === 1) return;

  model.value.status = e ? 0 : 1;
};
</script>

<template>
  <AppFooter>
    <div class="flex-center py-3" v-loading="isFetchingWithDetail">
      <ElButton class="px-12" size="large" :disabled="isFetching" @click="reset"
        >重置</ElButton
      >
      <ElButton
        type="primary"
        size="large"
        class="px-12"
        :loading="isFetching"
        @click="handleSubmit"
        >保存</ElButton
      >
    </div>
  </AppFooter>

  <div
    class="mx-auto"
    v-loading="isFetchingWithDetail"
    element-loading-text="正在加载数据"
  >
    <ElForm
      ref="refForm"
      label-width="7em"
      :rules="rules"
      :model="model"
      :loading="isFetching"
    >
      <ElCard header="基础信息">
        <ElFormItem label="活动名称" prop="title">
          <ElInput
            v-model="model.title"
            placeholder="请输入，最大30个字符"
            maxlength="30"
          />
        </ElFormItem>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="活动日期" class="w-full" prop="start_time">
              <DateRangePicker
                v-model:start="model.start_time"
                v-model:end="model.end_time"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12"></ElCol>

          <ElCol :span="12">
            <ElFormItem label="售票日期" class="w-full" prop="sale_start_time">
              <DateRangePicker
                v-model:start="model.sale_start_time"
                v-model:end="model.sale_end_time"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="早鸟日期" class="w-full">
              <DateRangePicker
                v-model:start="model.early_start_time"
                v-model:end="model.early_end_time"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>

          <!-- <ElCol :span="12"></ElCol> -->

          <ElCol :span="12">
            <ElFormItem label="展示日期" class="w-full" prop="act_time">
              <ElInput
                v-model="model.act_time"
                placeholder="活动时间优先显示当前内容"
                type="textarea"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="活动类型" class="w-full" prop="type">
              <ElRadioGroup v-model="model.type">
                <ElRadio
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElRadioGroup>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElCard>

      <ElCard header="主办方与位置" class="my-3">
        <ElFormItem label="主办方" prop="sponsor">
          <ElInput v-model="model.sponsor" placeholder="请输入主办方名称" />
          <!-- <ElSelect v-model="model.sponsor" class="w-full">
                        <ElOption v-for="item in sponsorList" :key="item.id" :value="item.id"
                                  :label="item.title" />
                    </ElSelect> -->
          <!-- <ElLink>新建主办方</ElLink> -->
        </ElFormItem>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="活动位置" prop="address">
              <ElInput
                v-model="model.address"
                placeholder="位置简称，如：深圳 高新区万达广场"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElSpace alignment="center">
              <ElFormItem label-width="0" prop="longitude">
                <ElInput v-model="model.longitude" placeholder="经度" />
              </ElFormItem>

              <ElFormItem label-width="0" prop="latitude">
                <ElInput v-model="model.latitude" placeholder="纬度" />
              </ElFormItem>

              <ElLink
                href="https://lbs.qq.com/tool/getpoint/get-point.html"
                target="_blank"
                >去取坐标
              </ElLink>
            </ElSpace>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem prop="street">
              <ElInput v-model="model.street" placeholder="详细地址" />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElInput
              v-model="pasteInput"
              placeholder="可在这里粘贴复制的坐标"
              @input="pasteChange"
            />
          </ElCol>
        </ElRow>
      </ElCard>

      <ElCard header="图文信息" class="my-3">
        <ElFormItem label="详情轮播图" prop="pic_content">
          <div>
            <ElSpace v-if="isSetCoverMode">
              <ElImage
                v-for="(item, index) in fileList"
                :key="index"
                class="w-100px h-100px border-#eee border-1 rounded-lg cursor-pointer hover:shadow-lg"
                :src="item.url"
                fit="contain"
                @click="setCoverFromFileList(item)"
              />
            </ElSpace>

            <Uploader
              v-else
              class="w-none"
              v-model:file-list="fileList"
              list-type="picture-card"
              :before-remove="handleBeforeRemove"
              :on-remove="handleRemove"
              @success="handleUploadSus"
            />
          </div>
        </ElFormItem>

        <ElFormItem label="封面图" prop="title_img">
          <div>
            <ElSpace>
              <UploaderSingle
                v-model="model.title_img"
                :before-remove="handleBeforeRemove"
                :on-remove="handleRemove"
                @success="handleUploadSus"
              />
              <div v-if="fileList.length > 0">
                <ElButton plain type="primary" @click="isSetCoverMode = true"
                  >详情轮播图中选择</ElButton
                >
              </div>
            </ElSpace>

            <div class="flex items-center mt-1">
              <ElText type="info">
                <el-icon><Warning /></el-icon>
              </ElText>

              <ElText class="text-sm" type="info"
                >详情主图/活动主图：1200:542
              </ElText>
            </div>
          </div>
        </ElFormItem>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="封面小图" prop="title_small_img">
              <div>
                <UploaderSingle v-model="model.title_small_img" />

                <div class="flex items-center">
                  <ElText type="info">
                    <el-icon><Warning /></el-icon>
                  </ElText>

                  <ElText class="text-sm ml-1" type="info"
                    >票夹插图/购买主图/活动分享：500:400</ElText
                  >
                </div>
              </div>
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="海报图" prop="poster_img">
              <div>
                <UploaderSingle v-model="model.poster_img" />

                <div class="flex items-center">
                  <ElText type="info">
                    <el-icon><Warning /></el-icon>
                  </ElText>

                  <ElText class="text-sm ml-1" type="info"
                    >购票成功海报/分享图：1266:1768</ElText
                  >
                </div>
              </div>
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElFormItem label="活动详情" prop="act_desc">
          <Editor v-model="model.act_desc" />
        </ElFormItem>

        <ElFormItem label="购票须知" prop="purchase_notice">
          <Editor v-model="model.purchase_notice" />
        </ElFormItem>

        <ElFormItem label="参展规则" prop="exhibition_rules">
          <Editor v-model="model.exhibition_rules" />
        </ElFormItem>
      </ElCard>

      <ElCard header="其他信息">
        <ElRow>
          <ElCol :span="12">
            <ElFormItem label="是否允许退款" label-width="7em">
              <ElSwitch
                v-model="model.is_refund"
                active-text="允许"
                :active-value="0"
                inactive-text="不允许"
                :inactive-value="1"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="活动是否显示">
              <div class="flex">
                <ElSwitch
                  v-model="model.is_show"
                  active-text="显示"
                  :active-value="0"
                  inactive-text="不显示"
                  :inactive-value="1"
                  @change="changeIsShow"
                />
              </div>

              <ElAlert type="error" :closable="false">
                提示：该状态一旦启用后；票券规格将不能重新生成，仅能编辑部分规格信息。
              </ElAlert>
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="是否开启招商">
              <ElSwitch
                v-model="model.inv_status"
                active-text="关闭"
                :active-value="0"
                inactive-text="开启"
                :inactive-value="1"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="是否开启售票">
              <ElSwitch
                v-model="model.is_ticket"
                active-text="开启"
                :active-value="1"
                inactive-text="关闭"
                :inactive-value="2"
              />
            </ElFormItem>
          </ElCol>

          <!-- <ElCol :span="12">
            <ElFormItem label="活动编辑状态" label-width="9em">
              <ElSwitch
                v-model="model.status"
                active-text="不可编辑"
                :active-value="1"
                inactive-text="正常"
                :inactive-value="0"
                disabled
              />

            </ElFormItem>
          </ElCol> -->

          <ElCol :span="12">
            <ElFormItem label="显示排序" prop="sort">
              <ProInputNumber
                v-model="model.sort"
                :min="0"
                :max="999"
                :precision="0"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElCard>
    </ElForm>
  </div>
</template>
